#define _CRT_SECURE_NO_WARNINGS 1

#include<iostream>
#include<vector>
#include<queue>

using namespace std;

int rotApple(vector<vector<int> >& grid) {
    int cnt = 0;
    int n = grid.size(), m = grid[0].size();
    int dx[4] = { 0,0,1,-1 };
    int dy[4] = { 1,-1,0,0 };
    queue<pair<int, int>> q;
    vector<vector<int>> st(n, vector<int>(m));
    for (int i = 0; i < n; i++)
        for (int j = 0; j < m; j++)
            if (grid[i][j] == 1)
                cnt++;
            else if (grid[i][j] == 2)
                q.push({ i,j });

    int res = 0;
    while (q.size())
    {
        auto t = q.front();
        q.pop();
        for (int i = 0; i < 4; i++)
        {
            int x = t.first + dx[i], y = t.second + dy[i];
            if (x < 0 || y < 0 || x >= n || y >= m)  continue;
            if (st[x][y])    continue;
            if (grid[x][y] != 1) continue;

            cnt--;
            st[x][y] = st[t.first][t.second] + 1;
            res = max(res, st[x][y]);
            q.push({ x,y });
        }
    }

    return cnt == 0 ? res : -1;
}

int LastRemaining(int n, int m) {
    if (n < 1 || m < 1)
        return -1;
    int last = 0;
    for (int i = 2; i <= n; i++)
        last = (last + m) % i;
    return last;
}